﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using WeatherService.Helpers;
using WeatherService.Storage;
using WeatherService.Types;

namespace WeatherService.DAC
{

    static class GetWeather
    {
       static  ADODB.Connection deltacon = new ADODB.Connection();
       static  ADODB.Recordset deltars = new ADODB.Recordset();

        public static void GetandApplyData()
        {
            getandapplyData();
        }
        private static void getandapplyData()
        {
            string sURL;
            string sLOC;
            string sAPI;
            string sDEVADD;
            string sltemp, shtemp, swspd, sctemp;
            string sDSN;
            string sOBJUPDATE1;
            string[] sCURRENT = new string[6];
            string[] sFORECAST = new string[30];
            Int16 iCURRCOUNT, iFORECOUNT, iXMLIND;
            Int16 iINST = 1;

            //set up variables based on user input
            
            
            
            sDSN = "Delta Network";

            //initialize the index and xml tags
            iCURRCOUNT = 2;
            iXMLIND = 1;
            


            try
            {
                var dataList = IsolatedStorageCacheManager<Weather>.DeserializeDataFromXML("weatherData");
                if (dataList!=null)
                {
                    if (dataList.Count>0)
                    {
                        sDEVADD = dataList[0].deviceInst;
                        sAPI = dataList[0].API;
                        sLOC = dataList[0].areaID;
                        sURL = "http://free.worldweatheronline.com/feed/weather.ashx?q=" + sLOC + "&format=xml&num_of_days=5&key=" + sAPI;
                        sltemp = dataList[0].slTemp;
                        shtemp = dataList[0].shTemp;
                        sctemp = dataList[0].scTemp;
                        swspd = dataList[0].swspd;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
                //get RSS feed from the website
                var webREQ = WebRequest.Create(sURL);
                var webRES = webREQ.GetResponse();
                //load RSS feed into an XML document
                var xmlResults = new XmlDocument();
                using (var retDATA = webRES.GetResponseStream())
                {
                    if (retDATA != null) xmlResults.Load(retDATA);
                }


                //Set up ODBC connection
                deltacon.ConnectionString = sDSN;
                deltacon.Open();
                deltars.ActiveConnection = deltacon;


                //current conditions---------------------------------------------------------------------------------------------------

                var xmlNode = xmlResults.GetElementsByTagName("query").Item(0);
                if (xmlNode != null)
                    sCURRENT[0] = xmlNode.InnerText;
                var item = xmlResults.GetElementsByTagName("weatherDesc").Item(0);
                if (item != null)
                    sCURRENT[1] = item.InnerText;
                var node = xmlResults.GetElementsByTagName(sctemp).Item(0);
                if (node != null)
                    sCURRENT[2] = node.InnerText;
                var xmlNode1 = xmlResults.GetElementsByTagName("windspeedKmph").Item(0);
                if (xmlNode1 != null)
                    sCURRENT[3] = xmlNode1.InnerText;
                var item1 = xmlResults.GetElementsByTagName("humidity").Item(0);
                if (item1 != null)
                    sCURRENT[4] = item1.InnerText;
                var node1 = xmlResults.GetElementsByTagName("precipMM").Item(0);
                if (node1 != null)
                    sCURRENT[5] = node1.InnerText;
                sOBJUPDATE1 = "UPDATE object_bac_AV SET Description = '" + sCURRENT[0] + " " + sCURRENT[1] + "' WHERE Dev_ID = " + sDEVADD + " and INSTANCE = 1";
                deltars.Open(sOBJUPDATE1);

                for (iCURRCOUNT = 2; iCURRCOUNT <= 5; iCURRCOUNT++)
                {
                    sOBJUPDATE1 = "UPDATE object_bac_AV set Value = " + sCURRENT[iCURRCOUNT] + " WHERE Dev_ID = " + sDEVADD + " and INSTANCE = " + iINST;
                    deltars.Open(sOBJUPDATE1);
                    iINST++;
                }



                //forecast conditions---------------------------------------------------------------------------------------------------
                for (iFORECOUNT = 0; iFORECOUNT < 27; iFORECOUNT += 7)
                {
                    var xmlNode2 = xmlResults.GetElementsByTagName("date").Item(iXMLIND);
                    if (xmlNode2 != null)
                        sFORECAST[iFORECOUNT] = xmlNode2.InnerText;
                    var item2 = xmlResults.GetElementsByTagName("weatherDesc").Item(iXMLIND);
                    if (item2 != null)
                        sFORECAST[iFORECOUNT + 1] = item2.InnerText;
                    var node2 = xmlResults.GetElementsByTagName(shtemp).Item(iXMLIND);
                    if (node2 != null)
                        sFORECAST[iFORECOUNT + 2] = node2.InnerText;
                    var xmlNode3 = xmlResults.GetElementsByTagName(sltemp).Item(iXMLIND);
                    if (xmlNode3 != null)
                        sFORECAST[iFORECOUNT + 3] = xmlNode3.InnerText;
                    var item3 = xmlResults.GetElementsByTagName(swspd).Item(iXMLIND);
                    if (item3 != null)
                        sFORECAST[iFORECOUNT + 4] = item3.InnerText;
                    sFORECAST[iFORECOUNT + 5] = xmlResults.GetElementsByTagName("weatherCode").Item(iXMLIND).InnerText;
                    sFORECAST[iFORECOUNT + 6] = xmlResults.GetElementsByTagName("precipMM").Item(iXMLIND).InnerText;
                    iXMLIND++;
                }

                iFORECOUNT = 0;

                while (iFORECOUNT < 28)
                {
                    if (iINST % 5 == 0)
                    {
                        sOBJUPDATE1 = "UPDATE object_bac_AV SET Description = '" + sFORECAST[iFORECOUNT + 1] + "' WHERE Dev_ID =" + sDEVADD + " and INSTANCE = " + iINST;
                        deltars.Open(sOBJUPDATE1);
                        iFORECOUNT += 2;
                        sOBJUPDATE1 = "UPDATE object_bac_AV set Value = " + sFORECAST[iFORECOUNT] + " WHERE Dev_ID = " + sDEVADD + " and INSTANCE = " + iINST;
                        deltars.Open(sOBJUPDATE1);
                        iINST += 1;
                        iFORECOUNT += 1;
                    }
                    else
                    {
                        sOBJUPDATE1 = "UPDATE object_bac_AV set Value = " + sFORECAST[iFORECOUNT] + " WHERE Dev_ID = " + sDEVADD + " and INSTANCE = " + iINST;
                        deltars.Open(sOBJUPDATE1);
                        iFORECOUNT += 1;
                        iINST += 1;
                    }

                }

                deltacon.Close();

                GC.Collect();
                GC.WaitForPendingFinalizers();
                System.Data.Odbc.OdbcConnection.ReleaseObjectPool();

            }
            catch (Exception)
            {
                Logger.ErrorLog("There was either an error generating the RSS feed or connecting to the ODBC driver. Please ensure that you have entered a valid www.worldwideweatheronline.com API key and have correctly configured the Delta ODBC driver");
                GC.Collect();
                GC.WaitForPendingFinalizers();
                System.Data.Odbc.OdbcConnection.ReleaseObjectPool();
            }
        }
    }
}
